#include "openssl_md5.h"
#include <openssl/md5.h>
#include <stdio.h>
#include "string.h"


/**
 * @brief Get the Md5 Str object
 * 返回32位的MD5
 * @param  data             My Param doc
 * @param  length           strlen(data)
 * @param  result           返回MD5值，空间要大于33
 * @return int 
 */
int getMd5Str(const char* data, int length, char* result, int byteSize)
{
    MD5_CTX c;
    MD5_Init(&c);
    MD5_Update(&c, data, length);

    unsigned char digest[16] = { 0 };
    char hexBuffer[3];
    MD5_Final(digest, &c);
    result[0] = '\0';
    for (size_t i = 0; i != 16; ++i)
    {
        if (digest[i] < 16)     sprintf(hexBuffer, "0%x", digest[i]);
        else                    sprintf(hexBuffer, "%x", digest[i]);
        strcat(result, hexBuffer);
    }
    result[32] = '\0';

    if(byteSize == 16)
    {
        char temp[17];
        // 如果格式化后的字符串长度大于等于 size，超过 size 的部分会被截断，只将其中的 (size-1) 个字符复制到 str 中，并给其后添加一个字符串结束符 \0，返回值为欲写入的字符串长度。
        snprintf(temp, 17, "%s", result + 8);
        temp[16] = '\0';
        sprintf(result, "%s", temp);
    }
    return 0;
}

int getMd5File(const char* filePath, char* result, int byteSize)
{
    FILE *file = fopen(filePath, "rb");
    if (file)
    {
        MD5_CTX c;
        MD5_Init(&c);
        
        char buffer[INPUT_BUFFER_SIZE];
        while (!feof(file))
        {
            size_t numberOfObjects = fread(buffer, sizeof(char), INPUT_BUFFER_SIZE, file);
            MD5_Update(&c, buffer, numberOfObjects);
        }
        fclose(file);

        unsigned char digest[16] = { 0 };
        char hexBuffer[3];
        MD5_Final(digest, &c);
        result[0] = '\0';
        for (size_t i = 0; i != 16; ++i)
        {
            if (digest[i] < 16)     sprintf(hexBuffer, "0%x", digest[i]);
            else                    sprintf(hexBuffer, "%x", digest[i]);
            strcat(result, hexBuffer);
        }
        result[32] = '\0';

        if(byteSize == 16)
        {
            char temp[17];
            snprintf(temp, 17, "%s", result + 8);
            temp[16] = '\0';
            sprintf(result, "%s", temp);
        }
    }
    else
    {
        return 1;
    }
    return 0;
}

